<template>
  <div>
    <ListTab v-model="activeId" :show-header="!showMobilePage" :tabs="tabList" :max-badge="{ num: 100, str: '99+' }" is-table @tabClick="handleTabClick" />
    <div :class="{'mobile-table mobile-min-height':showMobilePage}" class="table-list min-fill-page">
      <div v-if="!showMobilePage" class="filter">
        <FilterInput
          ref="FilterToolRef"
          v-model="paramsObj"
          :filter-list="filterList"
          show-search-btn
          is-show-config
          class="FilterTool"
          @handelClick="queryClick"
          @queryEmpty="queryEmpty"
          @filterTagStatus="filterTagStatus"
        />
        <div class="filter-more">
          <el-checkbox
            v-if="activeId === 0"
            v-model="isExpedited"
            :true-label="1"
            :false-label="0"
            class="checkbox-class"
            @change="setOnlyExpedited">仅展示加急</el-checkbox>
          <el-checkbox
            v-if="activeId === 3"
            v-model="onlyUnread"
            :true-label="1"
            :false-label="0"
            class="checkbox-class"
            @change="setOnlyUnread">仅未读</el-checkbox>
          <el-link
            v-if="activeId === 3"
            :disabled="list.items.length === 0"
            :underline="false"
            type="primary"
            @click="setAllRead">全部标记为已读</el-link>
        </div>
        <div class="opeator-bar">
          <el-button size="small" type="primary" style="height: 32px;" @click="toClearTodo">清理飞书待办</el-button>
        </div>
      </div>
      <div style="min-height: 100px">
        <u-table
          v-loading="listLoading"
          :data="list.items"
          :class="{ 'no-line': list.items.length > 0 }"
          :height="setTableHeight"
          :row-height="49"
          :border="true"
          beautify-table
          header-drag-style
          use-virtual
          class="fb-table todo-table"
          empty-text="暂无数据"
          header-cell-class-name="order-data-header-cell"
          fit
          hightlight-current-row
          row-class-name="pointer"
          @row-click="toDetail"
        >
          <EmptyPlaceholder
            slot="empty"
            mode="table"
            is-border
            style="padding-bottom: 0;"
          />
          <template v-for="(settingItem, index) in tableField">
            <u-table-column :key="index" v-bind="rowField[settingItem.field]" :width="settingItem.field === 'type' ? '120' : null">
              <template slot-scope="scope">
                <template v-if="activeId === 3 && settingItem.field === 'title'">
                  <div class="color-status-box">
                    <span v-if="!scope.row.read" class="dot" />
                    <ToolTip :content="scope.row.title" />
                  </div>
                </template>
                <template v-else-if="settingItem.field === 'type'">
                  <processSn :show-expedited="scope.row.isExpedited" :is-expedited="scope.row.isExpedited">
                    <p :class="`task-type type${scope.row.type}`">{{ scope.row.type | getTaskType }}</p>
                  </processSn>
                </template>
                <template v-else-if="settingItem.field === 'proposerName'">
                  <div class="column-creator">
                    <img :src="scope.row.avatar || avatarPng" alt="发起人">
                    <span>{{ scope.row.proposerName }}</span>
                  </div>
                </template>
                <template v-else-if="settingItem.field === 'publicDate'">
                  <div v-if="activeId === 3">{{ formatTime(scope.row.publicDate) }}</div>
                  <div v-else>{{ formatTime(scope.row.createTime) }}</div>
                </template>
                <template v-else-if="settingItem.field === 'currentNode'">
                  <ToolTip :content="scope.row.currentNode" />
                </template>
                <template v-else-if="settingItem.field === 'approvers'">
                  <ToolTip :content="scope.row.approvers" />
                </template>
                <template v-else-if="settingItem.field === 'approverDate'">
                  <div v-if="activeId === 3">{{ formatTime(scope.row.approverDate) }}</div>
                  <div v-else>{{ formatTime(scope.row.approveTime) }}</div>
                </template>
                <template v-else-if="settingItem.field === 'status'">
                  <div class="color-status-box">
                    <span v-if="scope.row.status !== null || scope.row.type" :style="{backgroundColor: formatStatus(scope.row, 3).color}" class="dot"/>
                    <p>{{ formatStatus(scope.row, 3).status }}</p>
                  </div>
                </template>
                <template v-else-if="settingItem.field === 'abstract'">
                  <template v-if="strJsonParse(scope.row.content) && scope.row.content !== '{}'">
                    <!-- <div v-for="(val, name) in strJsonParse(scope.row.content)" :key="name"> -->
                    <div v-for="(val, name) in formatAbstractData(scope.row.content)" :key="name">
                      <el-tooltip placement="top-start">
                        <div slot="content" style="max-width: 300px;">{{ `${name}：${val}` }}</div>
                        <div class="ellipsisOne" style="font-size: 12px">
                          <span style="color: #999">{{ name }}：</span>
                          <span>{{ (val || val === 0) ? val : '--' }}</span>
                        </div>
                      </el-tooltip>
                    </div>
                  </template>
                  <div v-else>--</div>
                </template>
              </template>
            </u-table-column>
          </template>
        </u-table>
      </div>
      <el-row v-if="showMobilePage && list.total > 0" type="flex" justify="left">
        <el-pagination
          :current-page.sync="list.page"
          :page-size="list.perPage"
          :total="list.total"
          :page-sizes="[20, 50, 100, 250, 500]"
          :layout="pageLayout"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
      <fixed-pagination v-show="list.total > 0 || showMobilePage">
        <template v-if="showMobilePage">
          <FilterInput
            ref="FilterToolRef"
            v-model="paramsObj"
            :filter-list="filterList"
            show-search-btn
            show-mobile-icon
            class="FilterTool"
            @handelClick="queryClick"
            @queryEmpty="queryEmpty"
            @filterTagStatus="filterTagStatus"
          />
          <MoreOpeator
            ref="moreOpeatorRef"
            :list="moreOperatorList"
            show-mobile-icon
          />
          <el-checkbox
            v-if="activeId === 0"
            v-model="isExpedited"
            :true-label="1"
            :false-label="0"
            class="checkbox-class"
            @change="setOnlyExpedited">仅展示加急</el-checkbox>
          <el-checkbox
            v-if="activeId === 3"
            v-model="onlyUnread"
            :true-label="1"
            :false-label="0"
            class="checkbox-class checkbox-right"
            @change="setOnlyUnread">仅未读</el-checkbox>
          <el-link
            v-if="activeId === 3"
            :disabled="list.items.length === 0"
            :underline="false"
            type="primary"
            @click="setAllRead">全部标记为已读</el-link>
        </template>
        <template v-else>
          <div style="flex: 1" />
          <el-pagination
            v-show="list.total > 0"
            :current-page.sync="list.page"
            :page-size="list.perPage"
            :total="list.total"
            :page-sizes="[20, 50, 100, 250, 500]"
            layout="total, prev, pager, next, sizes, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </template>
      </fixed-pagination>
    </div>
  </div>
</template>
<script>
import EmptyPlaceholder from '@/components/Common/emptyPlaceholder';
import ListTab from '@/components/ListTab';
import {
  getList,
  getReceiveList,
  setListRead
} from '@/api/todo';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
import { paramsRangeFormat } from '@/utils/paramsFormat';
import { showModal } from '@/utils/message';
import { EventBus } from '@/utils/eventBus';
import { strJsonParse } from '@/utils';
import TableAdaptive from '@/mixins/tableAdaptive';
import mobileTable from '@/mixins/mobileTable';
import { mapState } from 'vuex';
import axios from 'axios';
import { tableField, rowField } from './fieldData';
import Todo from '@/mixins/todo';
import clearActiveIcon from '@/assets/todo/clear-active.png';
import clearIcon from '@/assets/todo/clear.png';

export default {
  components: { ListTab, EmptyPlaceholder, MoreOpeator },
  mixins: [Todo, TableAdaptive, mobileTable],
  data() {
    return {
      clearIcon,
      clearActiveIcon,
      receiveListCancelToken: null,
      listCancelToken: null,
      tabList: [
        { id: 0, name: '待处理', num: 0 },
        { id: 1, name: '已处理', num: 0 },
        { id: 2, name: '我发起的', num: 0 },
        { id: 3, name: '我收到的', num: 0 }
      ],
      activeId: 0, // 当前选中tab的id
      listLoading: false,
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0
      },
      onlyUnread: 0,
      isExpedited: 0,
      paramsObj: {
        page: 1,
        perPage: 20,
        onlyUnread: 0
      },
      isUmyTable: true,
      isInit: true,
      tableField,
      rowField,
      clearLoading: false
    };
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo
    }),
    tableOutsideHeight() {
      return this.showMobilePage ? 204 : 0;
    },
    moreOperatorList() {
      return [
        { label: '清理飞书待办', handelClick: this.toClearTodo }
      ];
    }
  },
  created() {
    this.setTableFieldType();
  },
  beforeRouteEnter(to, from, next) {
    const formNames = [
      'approvalModuleDetail', 'todoDetail', 'contractDetail', 'supplierDetail', 'helpDetail', 'signUpDetail',
      'energyDetail', 'supplierManageDetail', 'originalDetail', 'originalDetail', 'handoverDetail', 'filterDetail',
      'invoiceAbandonDetail', 'issueInvoiceDetail', 'payBackDetail', 'loanDetail', 'reimbursementDetail', 'arrearsTransferDetail', 'terminationDetail'
    ];
    if (formNames.includes(from.name) && !from.query.fromDingDing) {
      to.meta.isChange = true;
    } else {
      to.meta.isChange = false;
    }
    next();
  },
  activated() {
    EventBus.$on('setAllRead', (msg) => {
      this.fetchData(true);
    });
    if (!this.$route.meta.isChange) {
      if (this.$route.query.activeId) {
        this.activeId = this.$route.query.activeId;
      }
      const hasDefaultPresetFilter = this.$refs.FilterToolRef && this.$refs.FilterToolRef.hasDefaultPresetFilter;
      if (!this.isInit || !hasDefaultPresetFilter) {
        this.fetchData(true);
      }
    } else {
      const activeId = ![null, 'false'].includes(localStorage.getItem('todoActiveId')) ? localStorage.getItem('todoActiveId') : '';
      this.activeId = Number(activeId) || 0;
      if (this.list && this.list.items && this.list.items.length === 0) {
        this.fetchData(true);
      } else {
        this.fetchData();
      }
    }
    localStorage.setItem('todoActiveId', this.activeId);// 缓存当前tab
  },
  methods: {
    strJsonParse,
    handleMonth(time = '') {
      return time ? time.replace(/-/g, '/') : '--';
    },
    setTableFieldType() {
      if (this.tableField[0]['field'] !== 'type') {
        this.tableField.splice(0, 0, { name: '任务类型', field: 'type' });
      }
    },
    async fetchData(reset = false) {
      this.listLoading = true;
      if (reset) {
        this.paramsObj.page = 1;
        this.paramsObj.perPage = 20;
        this.onlyUnread = 0;
        this.isExpedited = 0;
        this.paramsObj.onlyUnread = 0;
        this.paramsObj.isExpedited = 0;
      }
      this.getTabNums();
      const params = JSON.parse(JSON.stringify(this.paramsObj));
      paramsRangeFormat(this.rangeKeyArr, params);
      params.tabStatus = this.activeId;
      let res = {};
      if (this.activeId === 3) {
        if (this.listCancelToken) this.listCancelToken.cancel('cancel');
        if (this.receiveListCancelToken) {
          this.receiveListCancelToken.cancel('cancel');
        }
        const source = axios.CancelToken.source();
        this.receiveListCancelToken = source;
        res = await getReceiveList(params, source.token);
        const data = res.data.items;
        this.isInit = false;
        if (data.length > 0) {
          res.data.items = data.map((item) => {
            if (item.extendStr && this.isJSON(item.extendStr)) {
              const urlObj = JSON.parse(item.extendStr);
              item = { ...item, ...urlObj };
            }
            if (item.abstractStr && typeof item.abstractStr === 'string') {
              item.abstractStr = item.abstractStr.replace(/\n|\r/g, '');
            }
            if (item.abstractStr && this.isJSON(item.abstractStr)) {
              const urlObj = JSON.parse(item.abstractStr);
              item = { ...item, ...urlObj };
            }
            return item;
          });
        }
      } else {
        this.isInit = false;
        if (this.receiveListCancelToken) {
          this.receiveListCancelToken.cancel('cancel');
        }
        if (this.listCancelToken) this.listCancelToken.cancel('cancel');
        const source = axios.CancelToken.source();
        this.listCancelToken = source;
        res = await getList(params, source.token);
      }
      this.list = res.data;
      this.listLoading = false;
    },
    async getTabNums() {
      try {
        const { isExpedited, page, perPage } = this.paramsObj;
        const params = {
          page,
          perPage,
          isExpedited,
          tabStatus: 0
        };
        const params1 = {
          page,
          perPage,
          tabStatus: 3,
          onlyUnread: 1
        };
        const res = await getList(params);
        const result = await getReceiveList(params1);
        this.tabList[0].num = res.data.total;
        this.tabList[3].num = result.data.total;
        // 仅展示加急过滤只在列表过滤，不影响全局todo数量
        if (!isExpedited) {
          this.$store.commit('SETNOTICENUM', { total: res.data.total, unTotal: result.data.total });
        }
      } catch (error) {
        console.log(error);
      }
    },
    handleTabClick(id) {
      this.activeId = id;
      localStorage.setItem('todoActiveId', this.activeId);// 缓存当前tab
      if (this.activeId === 3) {
        this.tableField[0] = { name: '标题', field: 'title' };
      } else {
        this.tableField[0] = { name: '任务类型', field: 'type' };
      }
      this.list = { items: [] };
      this.fetchData(true);
    },
    queryClick() {
      this.fetchData();
    },
    queryEmpty() {
      this.paramsObj = {
        page: 1,
        perPage: 20
      };
      this.fetchData(true);
    },
    handleSizeChange(val) {
      this.paramsObj.perPage = val;
      this.fetchData();
    },
    handleCurrentChange(page) {
      this.paramsObj.page = page;
      this.fetchData();
    },
    async setSingleRead(row) {
      if (this.activeId === 3 && !row.read) {
        await this.setListRead(row.id);
        const index = this.list.items.findIndex((item) => {
          return item.id === row.id;
        });
        const item = this.list.items[index];
        item.read = true;
        this.$set(this.list.items, index, item);
        this.getTabNums();
      }
    },
    async setListRead(id) {
      await setListRead(id);
      if (id === -1) this.fetchData();
    },
    setAllRead() {
      showModal('请确认是否全部标记为已读', '', {
        iconClass: 'del-icon'
      })
        .then(() => {
          this.setListRead(-1);
        })
        .catch(() => {
          return false;
        });
    },
    setOnlyUnread(val) {
      this.paramsObj.onlyUnread = val;
      this.fetchData();
    },
    setOnlyExpedited(val) {
      this.paramsObj.isExpedited = val;
      this.fetchData();
    },
    toClearTodo() {
      this.$router.push({
        name: 'clearFeishuTodo'
      });
    }
  }
};
</script>

<style lang="scss" scoped>
@import "@/views/todo/todoTable.scss";
%flex {
  display: flex;
  align-items: center;
}
.table-list {
  margin: 16px 16px 0 16px;
  background-color: #fff;
  padding: 20px 20px 55px 20px;
}
.checkbox-class {
  @extend %flex;
  &::v-deep {
    .el-checkbox__input {
      .el-checkbox__inner {
        top: 0 !important;
      }
    }
  }
}
.checkbox-right {
  margin-right: 12px !important;
}
.filter {
  @extend %flex;
  position: relative;
  margin-bottom: 16px;
  .filter-more {
    @extend %flex;
    position: absolute;
    left: 502px;
    top: 7px;
    .el-checkbox {
      margin-left: 30px;
      &::v-deep .el-checkbox__label {
        padding-left: 4px !important;
      }
      &::v-deep .el-checkbox__inner {
        top: -2px;
      }
    }
    .el-link {
      font-size: 14px;
      margin-left: 24px;
    }
  }
  div {
    width: auto !important;
  }
  .opeator-bar {
    position: absolute;
    right: 0;
    display: flex;
    align-items: center;
    .clear-btn {
      background:#fff;
      padding: 0 6px;
      height:32px;
      // color:#406eff;
      img {
        width: 20px;
      }
    }
  }
}
.todo-table {
  &::v-deep {
    .el-table__empty-text {
      width: 100%;
    }
  }
}
.el-table {
  overflow-y: scroll;
  &.no-line {
    &::before {
      height: 0;
    }
    &::v-deep {
      .el-table__row:last-child td {
        border-bottom: 1px solid #ebeefd;
      }
    }
  }
  p {
    margin: 0;
  }
  .inline-block {
    display: inline-block;
    width: 100%;
  }
}
</style>
